package dao;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DataBaseOperation {
    private static DataSource dataSource = null;
    private static Properties properties = null;
    private static Connection connection = null;

    static{
        properties = new Properties();
        try {
            properties.load(DataBaseOperation.class.getResourceAsStream("../source/dataBase.properties"));
           dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据库连接池配置错误");
        }
    }

    //得到连接池对象
    public static DataSource getDataSource(){ return dataSource;}

    //得到连接池中连接对象
    public static Connection getConnection(){
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void  close(ResultSet result, PreparedStatement statement){
        try {
            if(connection != null) connection.close();
            if(result != null) result.close();
            if(statement != null) statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(PreparedStatement statement){
       close(null,statement);
    }


    public static PreparedStatement getConnectionAndStatement(String sql, PreparedStatement statement){
        connection = getConnection();
        try {
            statement = connection.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return statement;
    }
}
